<template>
  <div class="chatMessages-wrapper">
  </div>
</template>

<script>
import { getRootWindow } from '@src/util/dom/index.js'

import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { playMusic } from '@src/util/index.ts'
import { randomString } from '@src/util/lang/string'
/** components */
import CallPhone from '@src/modules/system/frame/component/globalWebSocket/components/renderMessage/CallPhone.vue'

export default {
  name: 'chat-messages',
  data() {
    return {
      messageList: [], // 气泡消息列表
      maxMessages: 3, // 同时显示气泡消息数
    };
  },
  created(){
    this.$eventBus.$on('socket-addMessage', this.addMessage);
  },
  destroyed () {
    this.$eventBus.$off('socket-addMessage', this.addMessage);
  },
  methods: {
    /**
     * addMessage 添加推送消息
     * @param {object} data 消息
     */
    addMessage(data = {}) {
      let messageInfo = data;
      let newMessageInfo;
      if (this.messageList.length >= this.maxMessages) {
        this.delFirstMessage();
      }
      if(messageInfo.notifyType == 'newMessage'){
        newMessageInfo = this.renderMessage(messageInfo);
      }
      // 内部在线客服
      if(messageInfo.notifyType == 'chatNewMessage' || messageInfo.notifyType == 'chatGroupNewMessage' || messageInfo.notifyType == 'chatNewGroup'){
        newMessageInfo = this.renderInsideImMessage(messageInfo);
      }
      // SDK专属客服
      if(messageInfo.notifyType == 'im-customerService'){
        newMessageInfo = this.renderCustomerServiceMessage()
      }
      // 400通知
      if(messageInfo.notifyType == 'productQrCodeCustomerAddLeavelMessage'){
        newMessageInfo = this.renderCallMessage(messageInfo)
      }
      // 自动上下班--呼叫中心
      if(messageInfo.notifyType == 'automaticWork'){
        newMessageInfo = this.renderCallCenterAutoWokMessage(messageInfo)
      }
      // 在线客服新会话通知，会话转交，会话指派
      if(['newConversation','forwardConversation','assignConversation'].includes(messageInfo.notifyType)){
        newMessageInfo = this.renderNewConversationMessage(messageInfo);
      }

      this.messageList.push(newMessageInfo);
    },

    /**
     * delMessage 删除某条消息气泡
     * @param {string} id 气泡消息唯一标识
     */
    delMessage(bizId) {
      this.messageList.splice(
        this.messageList.findIndex(v => v.bizId == bizId),
        1
      );
    },
    // 气泡消息卡片点击回调
    messageClick(messageInfo = {}) {
      const { instances } = messageInfo;
      // 1.跳转到在线客服
      this.toImPage(messageInfo);
      // 2.销毁气泡消息
      instances.close();
    },
    // 专属客服气泡消息卡片点击回调
    customerServiceMessageClick(messageInfo = {}) {
      const { instances } = messageInfo;
      // 1.显示弹窗
      this.$eventBus.$emit('im-customerService-open-chat')
      // 2.销毁气泡消息
      instances.close();
    },
    // 内部IM消息卡片点击回调
    insIdeImMessageClick(messageInfo = {}) {
      const { instances } = messageInfo;
      let win = getRootWindow(window);
      win?.insideImCardCb(messageInfo.content.chatUuid)
      sessionStorage.setItem('ImCardChatUuid', messageInfo.content.chatUuid)
      // 2.销毁气泡消息
      instances.close();
    },

    // 删除最前面一条消息
    delFirstMessage() {
      const { instances } = this.messageList[0];
      instances.close();
    },

    // 跳转到在线客服页
    toImPage(messageInfo) {
      let page = this.isOpenWindow('/im/imChat')
      let {conversationId} = messageInfo.content
      let url = '/im/imChat'
      if(page){
        page.contentWindow.postMessage({action:'shb.system.websocket', data:{notifyType:'toTargetConversation', conversationId}}, '*');
      }else{
        // url = `/im/imChat?id=${conversationId}`
        sessionStorage.setItem('im_conversationId', conversationId)
      }
      openAccurateTab({
        type: PageRoutesTypeEnum.PageImImchat,
        key:page?.getAttribute('data-id') || ''
      })
    },

    /**
     * renderMessage 渲染气泡消息
     * @param {object} data 气泡消息
     * @return {object} 带有气泡实例的气泡消息对象
     */
    renderMessage(data) {
      let messageInfo = data;
      let msgStr;
      const { titleName = '' } = messageInfo;
      let { messageFrom, messageType } = messageInfo.content
      let { msg } = messageInfo.content.messageContent;
      if (messageType == 'txt') {
        msgStr = `<div class="messageInfo">${messageFrom}：${msg}</div>`;
      } else {
        msgStr = `<div class="messageInfo">${messageFrom}：${'你有一条新消息'}</div>`;
      }
      messageInfo.instances = this.$notify({
        title:titleName,
        dangerouslyUseHTMLString: true,
        customClass: 'customer-service-message-push',
        offset: 100,
        message: msgStr,
        duration: 0,
        onClick: () => {
          this.messageClick(messageInfo);
        },
        onClose: () => {
          this.delMessage(messageInfo.bizId);
        },
      });
      return messageInfo;
    },
    // 渲染内部在线客服消息通知
    renderInsideImMessage(data) {
      let messageInfo = data;
      // let msgStr;
      const { titleName = '' } = messageInfo;
      let { sendUserName, groupName, groupHead, sendUserHead, chatType } = messageInfo.content
      let { msg, type } = messageInfo.content.messageContent;
      // if (type == 'text') {
      //   msgStr = `<div class="messageInfo">${sendUserName}：${msg}</div>`;
      // } else {
      //   msgStr = `<div class="messageInfo">${sendUserName}：${'你有一条新消息'}</div>`;
      // }
      const h = this.$createElement;
      messageInfo.instances = this.$notify({
        title: titleName,
        dangerouslyUseHTMLString: true,
        customClass: 'customer-service-message-push',
        offset: 100,
        message: h('div', { class: 'message-box' }, [
          h('img', {
            class: 'message-box-img',
            attrs: { src: chatType === 1 ? sendUserHead : groupHead },
          }),
          h('div', { class: 'message-box-content' }, [
            h('h3', {}, chatType === 1 ? sendUserName : groupName),
            h(
              'span',
              {},
              type === 'text'
                ? chatType === 1
                  ? msg
                  : `${sendUserName}：${msg}`
                : '你有一条新消息'
            ),
          ]),
        ]),
        duration: 0,
        onClick: () => {
          this.insIdeImMessageClick(messageInfo);
        },
        onClose: () => {
          this.delMessage(messageInfo.bizId);
        },
      });
      return messageInfo;
    },
    /**
     * isOpenWindow 判断某窗口是否打开
     * @param {string} url 窗口路径例如 /im/imChat
     * @return {dom} page 窗口dom对象
     */
    isOpenWindow(url){
      let page;
      let iframes = Array.from(document.getElementsByTagName('iframe'));
      page = iframes.find(item =>item.src.includes(url))
      return page
    },
    /**
     * renderCustomerServiceMessage 渲染SDK专属客服气泡消息
     * @return {object} 带有气泡实例的气泡消息对象
     */
     renderCustomerServiceMessage() {
      let messageInfo = {
        bizId:randomString()
      };
      messageInfo.instances = this.$notify({
        title:this.$t('frame.im.text1'),
        dangerouslyUseHTMLString: true,
        customClass: 'customer-service-message-push',
        offset: 100,
        message: this.$t('frame.im.text2'),
        duration: 0,
        onClick: () => {
          this.customerServiceMessageClick(messageInfo);
        },
        onClose: () => {
          this.delMessage(messageInfo.bizId);
        },
      });
      return messageInfo;
    },
    /**
     * renderCallPhoneMessage 渲染400通知消息
     * @return {object} 带有气泡实例的气泡消息对象
     */
     renderCallMessage(data) {
      let messageInfo = data
      messageInfo.instances = this.$notify({
        title:this.$t('system.customerNotification'),
        dangerouslyUseHTMLString: true,
        customClass: 'customer-service-message-push noPointer',
        offset: 100,
        message:this.$createElement(CallPhone,{
          props:{
            messageInfo
          }
        }),
        duration: 0,
        onClose: () => {
          this.delMessage(messageInfo.bizId);
        },
      });
      return messageInfo;
    }, 

    renderCallCenterAutoWokMessage(data) {
      let messageInfo = data;
      let msgStr;
      let { workIng = false } = messageInfo.content
      if (workIng) {
        msgStr = this.$t('system.callCenter.autoWorkTipMsg', {status: this.$t('common.base.usualStatus.working'), workStatus: this.$t('system.callCenter.work')});
      } else {
        msgStr = this.$t('system.callCenter.autoWorkTipMsg', {status: this.$t('common.base.usualStatus.resting'), workStatus: this.$t('system.callCenter.outOffWork')});
      }
      messageInfo.instances = this.$notify({
        title: this.$t('callcenter.callcenterAutoWork'),
        dangerouslyUseHTMLString: true,
        customClass: 'customer-service-message-push',
        offset: 100,
        message: msgStr,
        duration: 0,
        onClose: () => {
          this.delMessage(messageInfo.bizId);
        },
      });
      return messageInfo;
    },
    renderNewConversationMessage(data) {
      let messageInfo = data;
      messageInfo.instances = this.$notify({
        title:this.$t('im.imChat.tips3'),
        dangerouslyUseHTMLString: true,
        customClass: 'customer-service-message-push',
        offset: 100,
        message: this.$t('im.imChat.tips4'),
        duration: 0,
        onClick: () => {
          this.messageClick(messageInfo);
        },
        onClose: () => {
          this.delMessage(messageInfo.bizId);
        },
      });
      return messageInfo;
    },
  },
}
</script>

<style lang="scss">
.customer-service-message-push {
  cursor: pointer;
  &.noPointer{
    cursor: auto;
  }
  background: linear-gradient(109deg, #DFF8F4 0%, #FFFFFF 100%);
  .el-notification__group {
    width: 100%;
    .el-notification__title {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: bold;
      color: #595959;
      line-height: 14px;
    }
    .el-notification__content {
      width: 100%;
    }
  }
  .messageInfo {
    font-size: 16px;
    font-weight: bold;
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .message-box {
    display: flex;
    align-items: center;

    &-img {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      margin-right: 10px;
    }

    &-content {
      display: flex;
      flex-direction: column;

      h3 {
        width: 200px;
        font-size: 16px;
        margin-bottom: 2px;
        @include text-ellipsis;
      }

      span {
        width: 200px;
        font-size: 14px;
        color: #595959;
        @include text-ellipsis;
      }
    }
  }
}
</style>
